using System.Collections;
using System.IO;
using Microsoft.VisualBasic;
using Microsoft.VisualBasic.CompilerServices;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Runtime.CompilerServices;
using System.Windows.Forms;
using System.Data.OleDb;
using DevExpress.XtraEditors.Controls;
using System.Runtime.InteropServices;

namespace ePlanSysOman
{
    public partial class frmCrunch
    {
        public static frmCrunch newfrmCrunch1 = new frmCrunch();//JMR
        public OleDbDataAdapter daCBE = new OleDbDataAdapter();
        public OleDbDataAdapter daCrunch = new OleDbDataAdapter();
        public OleDbDataAdapter daMPRS = new OleDbDataAdapter();
        public OleDbDataAdapter daPTP = new OleDbDataAdapter();
        private int FRMO = 0;
        private int thru = 0;
        private string typever = "";
        private void SimpleButton3_Click(System.Object sender, System.EventArgs e)
        {
	        OpenFileDialog dialog = new OpenFileDialog();
	        clsData data = new clsData();
	        dialog.InitialDirectory = "c:\\";
	        dialog.Filter = "Microsoft Acess files (*.MDB)|*.MDB|All files (*.*)|*.*";

	        if ((dialog.ShowDialog() == DialogResult.OK)) {
		        DataSet aset = null;
		        string str2 = "";
		        string fileName = dialog.FileName;
		        if (fileName.EndsWith(".mdb")) {
			        DialogResult ansd = default(DialogResult);
			        clsData data2 = new clsData();
			        Module1.newModule.newconn = fileName;
			        str2 = "UPDATE tblEcn set COMMENT = 'Not planned' WHERE  comment not like '%pl%'";
			        data.ExecuteSQL(str2);
                    Module1.newModule.isCrunch = true;
			        try {
				        aset = data.getData("select *  from ECN_RCN_2818");
				        aset = null;

			        } catch (Exception ex) {
			        }
			        ansd = MessageBox.Show("Different ECP present. Do you want to continue", "Crunchrun", MessageBoxButtons.YesNo);
                    if (ansd == DialogResult.Yes) {
				        if (aset == null) {
					        string namesd = "";

					        DataTable userTables = null;
					        System.Data.OleDb.OleDbConnection connection = new System.Data.OleDb.OleDbConnection();
					        // c:\test\test.mdb
					        connection.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + fileName;
					        // We only want user tables, not system tables
					        string[] restrictions = new string[5];
					        restrictions[3] = "30";
					        connection.Open();
					        // Get list of user tables
					        userTables = connection.GetSchema("Tables");

					        // Add list of table names to listBox
					        int ir = 0;
					        for (ir = 0; ir <= userTables.Rows.Count - 1; ir += ir + 1) {
						        if (userTables.Rows[ir][2].ToString().Contains("ECN_RCN_")) {
							        namesd = userTables.Rows[ir][2].ToString();
						        }
					        }
					        aset = data.getData("select *  from " + namesd);
					        connection.Close();
				        }
			        } else {
				        return;
			        }

			        Module1.newModule.isCrunch = false;
			        int num3 = aset.Tables[0].Rows.Count;
			        int num4 = this.dsCrunch.Tables[0].Rows.Count;
			        num3 = (num3 - num4);




		        } else {
			        fileName = dialog.FileName;
			        OleDbConnection connection2 = new OleDbConnection();
			        connection2.ConnectionString = (("Provider=Microsoft.Jet.OLEDB.4.0; Data Source= " + fileName + ";Extended Properties=Excel 8.0;"));
			        connection2.Open();
			        string str3 = "select * from [Sheet1$]";
			        //                    New OleDbDataAdapter(str3, connection2).Fill(aset)
			        OleDbConnection connection = new OleDbConnection();
			        connection.ConnectionString = (("Provider=Microsoft.Jet.OLEDB.4.0; Data Source= " + Module1.newModule.ni));
			        connection.Open();
			        connection.Close();
		        }
		        int count = aset.Tables[0].Rows.Count;
		        int num5 = (count - 1);
		        int i = 0;
		        while ((i <= num5)) {
			        frmMain.start.spr1.Minimum = 0;
			        frmMain.start.spr1.Maximum = count;
			        string str5 = null;
			        DataSet set3 = new DataSet();
			        frmMain.start.spr1.Value = i;
			        frmMain.start.spr1.ProgressBar.Refresh();
			        try {
				        str5 = Conversions.ToString(aset.Tables[0].Rows[i]["ECN"]);

			        } catch (Exception ex) {
				        //jk = i
				        for (int jk = i; jk <= i + 25; jk++) {
					        bool fd = false;

					        try {
						        str5 = aset.Tables[0].Rows[jk]["ECN"].ToString();

					        } catch (Exception ex2) {
						        fd = true;

					        }
					        if (fd == true) {
						        fd = false;
					        } else {
						        break; // TODO: might not be correct. Was : Exit For
					        }
				        }
			        }


			        if ((data.getData(("SELECT * FROM TBLECN WHERE COMMENT <> '!NEW !' AND ECN ='" + str5 + "'")).Tables[0].Rows.Count <= 0)) {
				        //Me.lblpr.Text = "Importing records from Ecn."
				        //Me.lblpr.Refresh()
				        Module1.newModule.Ecns = true;
				        str2 = "insert into tblEcn " + Strings.ChrW(13) + Strings.ChrW(10);
				        str2 = Conversions.ToString(Operators.ConcatenateObject((str2 + "values ( "), Operators.ConcatenateObject(Operators.ConcatenateObject("'", aset.Tables[0].Rows[i]["DRAWING"]), "',")));
				        string str6 = Conversions.ToString(Interaction.IIf((object.ReferenceEquals(aset.Tables[0].Rows[i]["DWG REV"], DBNull.Value)), "-", RuntimeHelpers.GetObjectValue(aset.Tables[0].Rows[i]["DWG REV"])));
				        Module1.newModule.dash1 = Conversions.ToString(Interaction.IIf((object.ReferenceEquals(aset.Tables[0].Rows[i]["DASH"], DBNull.Value)), "-", RuntimeHelpers.GetObjectValue(aset.Tables[0].Rows[i]["DASH"])));
				        if (Module1.newModule.dash1.Contains("-")) {
					        Module1.newModule.dash1 = "----";
				        }
				        Module1.newModule.tv = Conversions.ToString(aset.Tables[0].Rows[i]["TYPE VER"]);
                        Module1.newModule.tv = Module1.newModule.tv.Trim();
                        Module1.newModule.DRAWIN = Conversions.ToString(aset.Tables[0].Rows[i]["DRAWING"]);
                        str2 = Conversions.ToString(Operators.ConcatenateObject(Conversions.ToString(Operators.ConcatenateObject(Conversions.ToString(Operators.ConcatenateObject(Conversions.ToString(Operators.ConcatenateObject(Conversions.ToString(Operators.ConcatenateObject((Conversions.ToString(Operators.ConcatenateObject(Conversions.ToString(Operators.ConcatenateObject(Conversions.ToString(Operators.ConcatenateObject((str2 + "'" + Module1.newModule.dash1 + "',"), Operators.ConcatenateObject(Operators.ConcatenateObject("'", Interaction.IIf((object.ReferenceEquals(aset.Tables[0].Rows[i]["DWG REV"], DBNull.Value)), "-", RuntimeHelpers.GetObjectValue(aset.Tables[0].Rows[i]["DWG REV"]))), "',"))), Operators.ConcatenateObject(Operators.ConcatenateObject("'", Interaction.IIf((object.ReferenceEquals(aset.Tables[0].Rows[i]["CHG LTR"], DBNull.Value)), "-", RuntimeHelpers.GetObjectValue(aset.Tables[0].Rows[i]["CHG LTR"]))), "',"))), Operators.ConcatenateObject(Operators.ConcatenateObject("'", str5), "',"))) + "'" + Module1.newModule.tv + "',"), Operators.ConcatenateObject(Operators.ConcatenateObject("'", aset.Tables[0].Rows[i]["FROM"]), "',"))), Operators.ConcatenateObject(Operators.ConcatenateObject("'", aset.Tables[0].Rows[i]["THRU"]), "',"))), Operators.ConcatenateObject(Operators.ConcatenateObject("'", Interaction.IIf((object.ReferenceEquals(aset.Tables[0].Rows[i]["DATE"], DBNull.Value)), "-", RuntimeHelpers.GetObjectValue(aset.Tables[0].Rows[i]["DATE"]))), "',"))), Operators.ConcatenateObject(Operators.ConcatenateObject("'", aset.Tables[0].Rows[i]["ECP/RCN"]), "',"))), Operators.ConcatenateObject(Operators.ConcatenateObject("'", Interaction.IIf((object.ReferenceEquals(aset.Tables[0].Rows[i]["DRAWING TITLE"], DBNull.Value)), "-", RuntimeHelpers.GetObjectValue(aset.Tables[0].Rows[i]["DRAWING TITLE"]))), "','!NEW !','')")));
				        data.ExecuteSQL(str2);
			        }
                    Module1.newModule.Ecns = false;
			        i += 1;
		        }
		        aset.Dispose();
		        DataSet set2 = new DataSet();
                Module1.newModule.Ecns = true;
                set2 = data.getData(("select * from tblEcn where COMMENT = '!NEW !' AND RCN LIKE'" + Module1.newModule.cmbthing + "%'"));
		        this.lblpr.Text = "Ecn records loaded.";
		        this.lblpr.Refresh();
		        frmMain.start.spr1.Value = count;
		        DevExpress.XtraEditors.XtraMessageBox.Show(("You have " + Conversions.ToString(set2.Tables[0].Rows.Count) + " new records."), "Ecn Crunch Run ", MessageBoxButtons.OK);
		        this.GridControl1.Refresh();
		        this.GridControl1.RefreshDataSource();
		        try {
			        this.daCrunch.Fill(this.dsCrunch, "tblEcn");
		        } catch (Exception exception1) {
			        ProjectData.SetProjectError(exception1);
			        Exception exception = exception1;
			        ProjectData.ClearProjectError();
		        }
	        }
	        frmWait wait = new frmWait();
        }

        private void  // ERROR: Handles clauses are not supported in C#
    SimpleButton1_Click(object sender, System.EventArgs e)
        {
            DataSet DSAS = new DataSet();
            clsData DSA = new clsData();
            DSAS = DSA.getData("SELECT DRAWING,ECN,TYPEVER,FR0M AS START,THRU,DRAWINGTITLE,COMMENT AS STATUS FROM TBLECN");
            ExportToExcel(DSAS.Tables[0]); // bjr - 9/28/2014
            //GridControl1.ShowPrintPreview()
        }
        private void ExportToExcel(System.Data.DataTable objDT)
        {

            ModuleWaitDialog.newModule2.CreateWaitDialog("Please wait..", "Ecn status.");//JMR
            this.Enabled = false;
            System.Globalization.CultureInfo oldCI = System.Threading.Thread.CurrentThread.CurrentCulture;
            System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en-US");

            //object Excel = CreateObject("Excel.Application");
            object Excel = Activator.CreateInstance(Type.GetTypeFromProgID("Excel.Application"));//JMR replaced above line 'quick and dirty way'
            string strFilename = "";
            int intCol;
            int intRow;
            string strPath = "c:\\";
            SaveFileDialog dlg = new SaveFileDialog();
            dlg.InitialDirectory = "Desktop";
            dlg.Filter = "Microsoft Excel files (*.xlsx)|*.xlsx|All files (*.*)|*.*";
            try
            {
                dlg.FileName = ("ECN STATUS FOR Oman " + System.DateTime.Today);
                dlg.FileName = dlg.FileName.Replace("/", "_");
            }
            catch (Exception ex)
            {
                dlg.FileName = "ECN STATUS";
            }
            if (Excel == null)
            {
                string error = "ERROR";
                string message = "It appears that Excel is not installed on this machine. This operation requires MS Excel to be installed on this machine.";
                MessageBox.Show(message, error);//JMR
                //MsgBox("It appears that Excel is not installed on this machine. This operation requires MS Excel to be installed on this machine.", MsgBoxStyle.Critical);
                return;
            }
            try
            {
                // ERROR: Not supported in C#: WithStatement





                Excel = null;
                // MsgBox("Data's are exported to Excel Succesfully in '" & strFilename & "'", MsgBoxStyle.Information)
            }
            catch (Exception ex)
            {
                ModuleWaitDialog.newModule2.CloseWaitDialog();//JMR
                MessageBox.Show(ex.Message);//JMR
            }
            // The excel is created and opened for insert value. We most close this excel using this system
            this.Enabled = true;

            System.Threading.Thread.CurrentThread.CurrentCulture = oldCI;
        }
        private void GridControl1_Click(System.Object sender, System.EventArgs e)
        {

        }

        private void  // ERROR: Handles clauses are not supported in C#
    frmCrunch_Activated(object sender, System.EventArgs e)
        {
            try
            {
                this.dsCrunch.AcceptChanges();
                this.daCrunch.AcceptChangesDuringUpdate = true;
                this.daCrunch.Update(this.dsCrunch, "tblEcn");
            }
            catch (Exception exception1)
            {
                ProjectData.SetProjectError(exception1);
                Exception exception = exception1;
                ProjectData.ClearProjectError();
            }
            try
            {
                OleDbCommand cmd = new OleDbCommand();
                cmd.Connection = Module1.newModule.Cn;
                cmd.CommandType = CommandType.Text;
                cmd.CommandText = "select * from tblEcn where  RCN LIKE '%'";
                daCrunch.SelectCommand = cmd;
                this.daCrunch.Fill(this.dsCrunch);
                GridControl1.Refresh();
                GridControl1.RefreshDataSource();
            }
            catch (Exception ex)
            {

            }
        }


        private void  // ERROR: Handles clauses are not supported in C#
    frmCrunch_Load(object sender, System.EventArgs e)
        {
            // Createadapter(dsCrunch, "tblEcn", "*", daCrunch)
            clsData DC = new clsData();
            DataSet DS = new DataSet();
            clsData data = new clsData();
            DataSet aset = new DataSet();
            Module1.newModule.Createadapter(this.dsCrunch, "tblEcn", (" RCN LIKE '" + Module1.newModule.cmbthing + "%'"), ref this.daCrunch);//JMR -- look at -- added ref


        }






        private void GridControl1_DoubleClick(object sender, System.EventArgs e)// ERROR: Handles clauses are not supported in C#
        {
            //bjr
            //DevExpress.XtraGrid.Columns.GridColumn ecn = 


            Module1.newModule.FormCloseex = false;

            //JMR
            Module1.newModule.stpParts = false;
            Module1.newModule.strEcn = Conversions.ToString(this.GridView1.GetRowCellValue(this.GridView1.GetSelectedRows()[0], "ECN"));
            Module1.newModule.DrwNo = Conversions.ToString(this.GridView1.GetRowCellValue(this.GridView1.GetSelectedRows()[0], "DRAWING"));
            Module1.newModule.tv = Conversions.ToString(this.GridView1.GetRowCellValue(this.GridView1.GetSelectedRows()[0], "TYPEVER"));
            Module1.newModule.strFrmo = Conversions.ToString(this.GridView1.GetRowCellValue(this.GridView1.GetSelectedRows()[0], "FR0M"));
            Module1.newModule.fr = Conversions.ToInteger(this.GridView1.GetRowCellValue(this.GridView1.GetSelectedRows()[0], "FR0M"));
            Module1.newModule.strTHRU = Conversions.ToString(this.GridView1.GetRowCellValue(this.GridView1.GetSelectedRows()[0], "THRU"));
            Module1.newModule.trhu = Conversions.ToInteger(this.GridView1.GetRowCellValue(this.GridView1.GetSelectedRows()[0], "THRU"));
            Module1.newModule.ECP = Conversions.ToString(this.GridView1.GetRowCellValue(this.GridView1.GetSelectedRows()[0], "RCN"));
            Module1.newModule.EFFECTIVITIES = Module1.newModule.ECP;
            Module1.newModule.ECP = Module1.newModule.ECP.Substring(0, 4);
            Module1.newModule.TITLE = Conversions.ToString(this.GridView1.GetRowCellValue(this.GridView1.GetSelectedRows()[0], "DRAWINGTITLE"));
            Module1.newModule.DRWREV = Conversions.ToString(this.GridView1.GetRowCellValue(this.GridView1.GetSelectedRows()[0], "DASH"));
            Module1.newModule.ProgramId = Conversions.ToString(this.GridView1.GetRowCellValue(this.GridView1.GetSelectedRows()[0], "COMMENT"));
            FRMO = Module1.newModule.fr;
            typever = Module1.newModule.tv;
            thru = Conversions.ToInteger(Module1.newModule.strTHRU);//JMR
            DataSet aset = new DataSet();
            clsData data2 = new clsData();
            clsData data = new clsData();

            var thirteen = char.ConvertFromUtf32((int)13); //changed from ChrW(13)    JMR
            var ten = char.ConvertFromUtf32((int)10); //changed from ChrW(10)         JMR

            if (LikeOperator.LikeString(Module1.newModule.DrwNo, "*H16DW*", CompareMethod.Binary))
            {
                if ((data2.getData(("select DISTINCT PART_NUMBER,DWG from PTP where DWG ='" + Module1.newModule.DrwNo + "'")).Tables[0].Rows.Count == 0))
                {
                    DevExpress.XtraEditors.XtraMessageBox.Show("No harness data found in database! " + thirteen + ten + " Select other drawing");
                }
                else
                {
                    frmMain.start.txtDrawing.Text = Module1.newModule.strEcn;
                    frmMain.start.txtDrawing.Text = Module1.newModule.TITLE;
                    if (((((((Module1.newModule.ProgramId == "") | LikeOperator.LikeString(Module1.newModule.ProgramId, "*NEW*", CompareMethod.Binary)) | (Module1.newModule.ProgramId == "Not planned")) | (Module1.newModule.ProgramId == "Not Planned")) | (Module1.newModule.ProgramId.Trim() == "")) | (Module1.newModule.ProgramId.Trim() == ",")))
                    {
                        Module1.newModule.ecnComment = "";
                        Module1.newModule.stath = Module1.newModule.strEcn;
                        DevExpress.XtraEditors.XtraMessageBox.Show("You have  select an ecn now select an area from the left!", "Select Area", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                        Module1.newModule.startinG = true;
                    }
                    else if ((DevExpress.XtraEditors.XtraMessageBox.Show(("Already using  ECN on " + Module1.newModule.ProgramId + thirteen + ten + "Do you want to use this ECN for another Planning card?"), "Add to card?", MessageBoxButtons.YesNo) == DialogResult.Yes))
                    {
                        Module1.newModule.startAgain = true;
                        DevExpress.XtraEditors.XtraMessageBox.Show("You have  select an ecn now select an area from the left!", "Select Area", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                        Module1.newModule.startinG = true;
                        Module1.newModule.stath = Module1.newModule.strEcn;
                        Module1.newModule.ecnComment = Module1.newModule.ProgramId;
                    }
                    else
                    {
                        Module1.newModule.startinG = false;
                    }
                }
            }
            else
            {
                frmMain.start.txtDrawing.Text = Module1.newModule.strEcn;
                frmMain.start.txtDrawing.Text = Module1.newModule.TITLE;
                if ((((((Module1.newModule.ProgramId == "") | LikeOperator.LikeString(Module1.newModule.ProgramId, "*NEW*", CompareMethod.Binary)) | (Module1.newModule.ProgramId == "Not planned")) | (Module1.newModule.ProgramId.Trim() == "")) | (Module1.newModule.ProgramId.Trim() == ",")))
                {
                    Module1.newModule.ecnComment = "";
                    Module1.newModule.stath = Module1.newModule.strEcn;
                    DevExpress.XtraEditors.XtraMessageBox.Show("You have  select an ecn now select an area from the left!", "Select Area", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    Module1.newModule.startinG = true;
                }
                else if ((DevExpress.XtraEditors.XtraMessageBox.Show(("Already using  ECN on " + Module1.newModule.ProgramId + thirteen + ten + "Do you want to use this ECN for another Planning card?"), "Add to card?", MessageBoxButtons.YesNo) == DialogResult.Yes))
                {
                    Module1.newModule.startAgain = true;
                    DevExpress.XtraEditors.XtraMessageBox.Show("You have  select an ecn now select an area from the left!", "Select Area", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    Module1.newModule.startinG = true;
                    Module1.newModule.stath = Module1.newModule.strEcn;
                    Module1.newModule.ecnComment = Module1.newModule.ProgramId;
                }
                else
                {
                    Module1.newModule.startinG = false;
                }
            }




        }


        private void  // ERROR: Handles clauses are not supported in C#
    CheckEdit1_CheckedChanged(System.Object sender, System.EventArgs e)
        {
            try
            {
                this.daCrunch.AcceptChangesDuringUpdate = true;
                this.daCrunch.Update(this.dsCrunch, "tblEcn");
            }
            catch (Exception exception1)
            {
                ProjectData.SetProjectError(exception1);
                Exception exception = exception1;
                ProjectData.ClearProjectError();
            }
            this.GridView1.OptionsBehavior.Editable = (this.CheckEdit1.CheckState > CheckState.Unchecked);
            this.GridControl1.EmbeddedNavigator.Visible = true;
            if (this.CheckEdit1.Checked)
            {
                this.GridView1.Columns["COMMENT"].VisibleIndex = 12;//JMR assembly: System.Web    namespace:System.Web.UI.WebControls
            }
            else
            {
                this.GridView1.Columns["COMMENT"].VisibleIndex = -1;
            }
        }

        private void  // ERROR: Handles clauses are not supported in C#
    GridView1_InitNewRow(object sender, DevExpress.XtraGrid.Views.Grid.InitNewRowEventArgs e)
        {
            this.GridView1.SetRowCellValue(this.GridView1.FocusedRowHandle, "DAT", "-");
            this.GridView1.SetRowCellValue(this.GridView1.FocusedRowHandle, "FIELD", "-");
        }
               
        public frmCrunch()
        {
            InitializeComponent();
        }
    }
}

